<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .wrap {
            width: 500px;
            /* border: 2px solid deeppink; */
            margin: 200px auto;
        }

        #content {
            height: 200px;
            max-width: 300px;
            overflow-y: scroll;
            border: 1px solid deepskyblue;
            font-size: 12px;
            color: #666;
            padding-left: 10px;
        }

        .mask {
            position: fixed;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, .5);
            color: #fff;
        }
    </style>

<body>
    <!-- <div class="mask">
            <h1>正在断开连接...</h1>
        </div> -->
    <div class="wrap">
        <input type="text" id="nickname" placeholder="输入昵称">
        <button id="connect">连接</button>
        <button id="close">断开</button>
        <div id="content"></div>
        <input type="text" id="msg">
        <button id="send">发送</button>
    </div>
</body>

</html>
<script>
    const input1 = document.querySelector("#nickname");
    const connect = document.getElementById("connect");
    const close = document.getElementById("close");
    const content = document.getElementById("content")
    const msg = document.getElementById("msg");
    const send = document.getElementById("send")

    //1.断开按钮 msg输入框 发送按钮处于禁用状态
    close.disabled = true;
    msg.disabled = true;
    send.disabled = true;
    //2.点击连接,需要使用websocket和服务器建立连接
    connect.onclick = function () {
        let nickname = input1.value;
        let ws = new WebSocket("ws://chst.vip:5200");
        ws.onopen = function () {
            console.log("连接成功");
            ws.send(nickname);
            close.disabled = false;
            msg.disabled = false;
            send.disabled = false;
            connect.disabled = true;
            input1.disabled = true;
        }
        //3.获取msg输入框的内容,点击发送按钮发送给服务器
        send.onclick = function () {
            let message = msg.value;
            ws.send(message);
        }
        //4.收到服务器的消息,展示在聊天框
        ws.onmessage = function (e) {
            let val = e.data;
            let p = document.createElement("p");
            p.innerHTML = val;
            content.appendChild(p);
            content.scrollTop = content.scrollHeight;
        }
        ws.onclose = function () {
            console.log("断开连接");
            close.disabled = true;
            msg.disabled = true;
            send.disabled = true;
            connect.disabled = false;
            input1.disabled = false;
        }
        close.onclick = function () {
            ws.close()
        }
    }
</script>